import { Module, VuexModule, Action } from "vuex-class-modules";
import { AuthMenus, MenuType } from "./MenuStore";
import { orderBy, sortBy } from "lodash";

const CACHE_KEY = "setting:sidebar-opened";

/**
 * 获取侧边栏展开状态
 * @returns
 */
function getSidebarOpened() {
  const opened = localStorage.getItem(CACHE_KEY);
  return Boolean(Number(opened));
}

/**
 * 设置侧边栏展开状态
 * @param opened
 */
function setSidebarOpened(opened: boolean) {
  localStorage.setItem(CACHE_KEY, opened ? "1" : "0");
}

@Module({ generateMutationSetters: true })
export default class AppStore extends VuexModule {
  sidebarOpened = getSidebarOpened();
  appName = process.env.VUE_APP_COMPANY;
  showMessagePanel = false; // 默认不显示
  messagePanelActiveTab = "Messages"; // 显示的消息面板
  // 权限菜单
  get authMenus() {
    return AuthMenus;
  }
  /** 默认显示的菜单 */
  get defaultDisplayMenus() {
    // 仅针对路由视图的菜单提取默认显示
    return sortBy(
      this.routerViewMenus.filter(f => f.isDefault),
      "order"
    );
  }
  /** 所有具有权限的路由菜单 */
  get routerViewMenus() {
    return this.authMenus.filter(f => f.menuType === MenuType.TabRouterView);
  }
  /** 作为路由菜单的home页 */
  get homeMenu() {
    if (this.routerViewMenus.length > 0) {
      // 排序时由于true 为 1 false 为 0 ，所以针对bool字段按倒序排序
      return orderBy(this.routerViewMenus, ["isDefault", "isHome", "order"], ["desc", "desc", "asc"])[0];
    }
  }
  /** 左侧菜单树 */
  get SidebarMenuTree() {
    const authMenus = this.authMenus;

    function findChildrens(code) {
      return sortBy(
        authMenus.filter(f => f.pcode && f.pcode === code && f.isVisibled).map(s => ({ ...s, childrens: findChildrens(s.code) })),
        "order"
      );
    }

    return sortBy(
      authMenus.filter(f => !f.pcode && f.isVisibled).map(s => ({ ...s, childrens: findChildrens(s.code) })),
      "order"
    );
  }

  /**
   *  切换左侧菜单的显示状态
   */
  @Action
  async toggleSideBar() {
    const sidebarOpened = !this.sidebarOpened;
    this.sidebarOpened = sidebarOpened;
    setSidebarOpened(sidebarOpened);
  }
  /**
   * 设置消息面板的显示状态
   * @param visible
   */
  @Action
  async setMessagePanelVisible(visible) {
    this.showMessagePanel = visible;
  }

  /**
   * 设置面板消息激活的tab
   * @param activeTab
   */
  @Action
  async setMessagePanelActiveTab(activeTab: "Messages" | "TodoItems" | "BackgroundTask") {
    this.messagePanelActiveTab = activeTab;
  }
}
